package engine

import (
	"log"
)

type ConcurrentQueue struct {
	Scheduler Scheduler
	WorkerCount int
}


func (e *ConcurrentQueue) Run(seeds ...Request)  {
	out:=make(chan ParseResult)
    e.Scheduler.Run()
	for i:=0;i<e.WorkerCount ;i++  {
		createWorkeQue(out,e.Scheduler)
	}

	for _,r:=range seeds{
		e.Scheduler.Submit(r)
	}

	for {
		result:=<-out
		for _,item:=range result.Items{
			log.Printf("%s",item)
		}
		for _,request:=range result.Requests{
			e.Scheduler.Submit(request)
		}
	}
}

func createWorkeQue(out chan  ParseResult,s Scheduler)  {
	in:=make(chan Request)
	go func() {
		for {
            s.WorkerReady(in)
            request:=<-in
            result,err:=worker(request)
			if err!=nil {
				continue
			}
            out<-result
		}
	}()
}
